package com.uenpay.im.ui.contacts;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.mcxtzhang.indexlib.IndexBar.widget.IndexBar;
import com.mcxtzhang.indexlib.suspension.SuspensionDecoration;
import com.qyx.android.database.FriendDB;
import com.qyx.android.entity.FriendEntity;
import com.uenpay.im.BroadcastAction;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.R2;
import com.uenpay.im.adapter.ContactsIndexAdapter;
import com.uenpay.im.entities.ContactsIndexBean;
import com.uenpay.im.entities.PopupEntity;
import com.uenpay.im.ui.old.activity.chat.ActivityHandle;
import com.uenpay.im.ui.old.activity.contacts.NewFriendsActivity;
import com.uenpay.im.ui.old.activity.contacts.SearchFriendsActivity;
import com.uenpay.im.ui.old.activity.group.MyGroupsActivity;
import com.uenpay.im.ui.old.activity.label.LabelListActivity;
import com.uenpay.im.ui.old.activity.publicnumber.MyPublicNumberListActivity;
import com.uenpay.im.utilities.DensityUtils;
import com.uenpay.im.weight.DividerItemDecoration;
import com.uenpay.util.app.base.BaseActivity;
import com.uenpay.util.widget.selector.AlphaSelector;
import com.uenpay.util.widget.selector.SelectorProcessor;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by PS on 2017/5/4.
 */
@Route(path = "/app/contacts")
public class ContactsActivity extends BaseActivity implements ContactsContract.View {

    private static final String INDEX_STRING_TOP = "↑";

    @BindView(R2.id.rv_contacts)
    RecyclerView rvContacts;
    @BindView(R2.id.tv_sidebar_hint)
    TextView tvSideBarHint;
    @BindView(R2.id.index_bar)
    IndexBar indexBar;
    @BindView(R2.id.tv_title)
    TextView tvTitle;

    private ArrayList<FriendEntity> friends;
    private ContactsActivity.showMsgBroadcastReceiver msgBroadcastReceiver = null;
    private Activity mContext = null;

    private ContactsIndexAdapter mContactsAdapter;
    private LinearLayoutManager mManager;
    private List<ContactsIndexBean> mDatas = new ArrayList<>();

    private SuspensionDecoration mDecoration;

    private ContactsContract.Presenter mContactsPresenter;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
    }

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_contacts_layout;
    }

    @Override
    public void initView(View view) {
        setTitle("通讯录");
        setRightBtnBackGround(R.drawable.ic_contacts_add);
        initView();
        initListener();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (friends == null) {
            refresh(false);
        }
        if (IMApplication.config.getIsNewFriend() > 0) {
            setNewFriends(IMApplication.config.getIsNewFriend());
        }
        if (msgBroadcastReceiver == null) {
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(BroadcastAction.SHOW_NEW_FRIENDS_ACTION);
            intentFilter.addAction(BroadcastAction.DELETE_FRIEND_ACTION);
            intentFilter.addAction(BroadcastAction.ACTION_AGREE_REQUEST);
            intentFilter.addAction(BroadcastAction.ACTION_REFRESH_FRIEND);
            intentFilter.addAction(BroadcastAction.ACTION_REFRESH_ORG);
            intentFilter.addAction(BroadcastAction.ACTION_REFRESH_AVATAR);
            intentFilter.addAction(BroadcastAction.ACTION_REFRESH_FRIEND_NAME);
            msgBroadcastReceiver = new ContactsActivity.showMsgBroadcastReceiver();
            mContext.registerReceiver(msgBroadcastReceiver, intentFilter);
        }
    }

    @Override
    public void onDestroy() {
        if (msgBroadcastReceiver != null) {
            mContext.unregisterReceiver(msgBroadcastReceiver);
        }
        super.onDestroy();
    }

    @Override
    public void setPresenter(ContactsContract.Presenter presenter) {
        mContactsPresenter = new ContactsPresenter(this);
    }

    @Override
    public void showToast(String msg) {

    }

    protected void initView() {
        rvContacts.setLayoutManager(mManager = new LinearLayoutManager(this));
        mContactsAdapter = new ContactsIndexAdapter(this, mDatas);
        rvContacts.setAdapter(mContactsAdapter);
        rvContacts.addItemDecoration(mDecoration = new SuspensionDecoration(this, mDatas));
        //如果add两个，那么按照先后顺序，依次渲染。
        rvContacts.addItemDecoration(new DividerItemDecoration(ContactsActivity.this, DividerItemDecoration.VERTICAL_LIST));

        indexBar.setmPressedShowTextView(tvSideBarHint)//设置HintTextView
                .setNeedRealIndex(true)//设置需要真实的索引
                .setmLayoutManager(mManager)//设置RecyclerView的LayoutManager
                .setMaxGapHeight(DensityUtils.dip2px(20));

        mContactsAdapter.setItemClickListener(new ContactsIndexAdapter.onRecyclewItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                doClick(view, position);
            }
        });
    }

    @Override
    public void onRightBtnInTopBarClick() {
        super.onRightBtnInTopBarClick();
        Intent intent = new Intent(ContactsActivity.this, SearchFriendsActivity.class);
        startActivity(intent);
    }

    protected void initListener() {

    }

    private void doClick(View view, int position) {
        switch (mDatas.get(position).getType()) {
            case ContactsIndexBean.CONTACTS_TYPE_SEARCH:
                Toast.makeText(ContactsActivity.this, "你点击了搜索框！", Toast.LENGTH_SHORT).show();
                break;
            case ContactsIndexBean.CONTACTS_TYPE_TOP:
                if (position == 1) {
                    Intent intent = new Intent(mContext, NewFriendsActivity.class);
                    mContext.startActivity(intent);
                    setNewFriends(0);
                    IMApplication.IS_GET_ALL_FRIENDS = true;
                } else if (position == 2) {
                    Intent intent = new Intent(mContext, MyGroupsActivity.class);
                    mContext.startActivity(intent);
                } else if (position == 3) {
                    Intent intent = new Intent(mContext, LabelListActivity.class);
                    mContext.startActivity(intent);
                } else if (position == 4) {
                    Intent intent = new Intent(mContext, MyPublicNumberListActivity.class);
                    mContext.startActivity(intent);
                }
                break;
            case ContactsIndexBean.CONTACTS_TYPE_COMMON:
                if (mDatas != null && mDatas.get(position).getFriendEntity() != null) {
                    ActivityHandle.startUserDetailActivity(mContext, mDatas.get(position).getFriendEntity().cust_id);
                }
                break;
            default:
                break;
        }
    }

    private void refresh(boolean is_refresh) {
        if (is_refresh || friends == null) {
            friends = null;
            friends = FriendDB.getFriends();
            Message msg = myHandler.obtainMessage();
            msg.what = 0;
            myHandler.sendMessage(msg);
        }

        if (is_refresh) {
            friends = null;
            friends = FriendDB.getFriends();
            myHandler.sendEmptyMessage(1);
        }
    }


    private ArrayList<PopupEntity> getPopData() {
        ArrayList<PopupEntity> arrayList = new ArrayList<PopupEntity>();
        PopupEntity entity = new PopupEntity(R.drawable.icon_pop_chat, R.string.start_group, 1);
        PopupEntity entity1 = new PopupEntity(R.drawable.icon_pop_newfriend, R.string.add_friends, 2);
        arrayList.add(entity);
        arrayList.add(entity1);
        return arrayList;
    }

    public class showMsgBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(BroadcastAction.DELETE_FRIEND_ACTION)) {
                refresh(true);
            } else if (intent.getAction().equals(BroadcastAction.ACTION_AGREE_REQUEST)) {
                refresh(true);
            } else if (intent.getAction().equals(BroadcastAction.ACTION_REFRESH_FRIEND)
                    || intent.getAction().equals(BroadcastAction.ACTION_REFRESH_FRIEND_NAME)) {
                refresh(true);
            } else if (intent.getAction().equals(BroadcastAction.SHOW_NEW_FRIENDS_ACTION)) {
                setNewFriends(Integer.parseInt(intent.getStringExtra("count")));
            } else if (intent.getAction().equals(BroadcastAction.ACTION_REFRESH_ORG)) {

            } else if (intent.getAction().equals(BroadcastAction.ACTION_REFRESH_AVATAR)) {
                if (mContactsAdapter != null) {
                    mContactsAdapter.notifyDataSetChanged();
                }
            }
        }
    }

    private Handler myHandler = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 0) {
                initData();
            } else if (msg.what == 1) {
                initData();
            }
            return false;
        }
    });

    private void setNewFriends(int count) {
        if (mDatas.size() > 0) {
            mDatas.get(1).setUnreadNum(count);
            mContactsAdapter.notifyItemChanged(1);
        }
    }


    private void initData() {
        mDatas = new ArrayList<>();
        //微信的头部 也是可以右侧IndexBar导航索引的，
        // 但是它不需要被ItemDecoration设一个标题titile
        mDatas.add((ContactsIndexBean) new ContactsIndexBean(ContactsIndexBean.CONTACTS_TYPE_SEARCH, true).setBaseIndexTag(INDEX_STRING_TOP));
        mDatas.add((ContactsIndexBean) new ContactsIndexBean("新的朋友", R.drawable.icon_new_friend, true, ContactsIndexBean.CONTACTS_TYPE_TOP).setBaseIndexTag(INDEX_STRING_TOP));
        mDatas.add((ContactsIndexBean) new ContactsIndexBean("群聊", R.drawable.icon_my_group, true, ContactsIndexBean.CONTACTS_TYPE_TOP).setBaseIndexTag(INDEX_STRING_TOP));
        mDatas.add((ContactsIndexBean) new ContactsIndexBean("服务号", R.drawable.icon_lable, true, ContactsIndexBean.CONTACTS_TYPE_TOP).setBaseIndexTag(INDEX_STRING_TOP));
        mDatas.add((ContactsIndexBean) new ContactsIndexBean("生活圈", R.drawable.icon_public_num, true, ContactsIndexBean.CONTACTS_TYPE_TOP).setBaseIndexTag(INDEX_STRING_TOP));
        for (int i = 0; i < friends.size(); i++) {
            ContactsIndexBean contactsIndexBean = new ContactsIndexBean();
            contactsIndexBean.setFriendEntity(friends.get(i));
            contactsIndexBean.setTop(false);
            contactsIndexBean.setName(friends.get(i).nick_name);//设置城市名称
            contactsIndexBean.setType(ContactsIndexBean.CONTACTS_TYPE_COMMON);
            mDatas.add(contactsIndexBean);
        }
        mDatas.add((ContactsIndexBean) new ContactsIndexBean(ContactsIndexBean.CONTACTS_TYPE_BOTTOM, friends.size()).setTop(true).setBaseIndexTag("#"));
        mContactsAdapter.setDatas(mDatas);
        mContactsAdapter.notifyDataSetChanged();

        indexBar.setmSourceDatas(mDatas)//设置数据
                .invalidate();
        mDecoration.setmDatas(mDatas);
        if (IMApplication.config.getIsNewFriend() > 0) {
            setNewFriends(IMApplication.config.getIsNewFriend());
        }

    }
}
